package com.czl.module_service.viewmodel

import android.os.Bundle
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.PurchaseBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

class PurchaseApplyInfoViewModel(application: MyApplication, model: DataRepository) :
    ApprovalFlowViewModel(application, model) {

    val uc = UiChangeEvent()
    var bean = ObservableField(PurchaseBean())
    var note = ObservableField("")
    var tabIndex : Int = 1
    var applicaitonId : Int? = null
    var taskUserId : String? = null

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<PurchaseBean> = SingleLiveEvent()
        val backCompleteEvent: SingleLiveEvent<Any> = SingleLiveEvent()
    }

    val onBackClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 撤销审批
        checkApplication(applicaitonId = applicaitonId, status = 3)
    })

    val onAgreeClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 同意
        nextTaskProcess(taskUserId = taskUserId)
    })

    val onRejectClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 驳回
        hangUpTaskProcess(taskUserId = taskUserId)
    })

    val onImageClick : BindingCommand<Any> = BindingCommand(BindingAction {
        val fileUrl = bean.get()?.fileParamUrl
        if (fileUrl!!.contains(".jpg") || fileUrl.contains(".jpeg") || fileUrl.contains(".png")) {
            val bundle = Bundle()
            bundle.putString(AppConstants.BundleKey.SHOW_BIG_IMG, fileUrl)
            startContainerActivity(
                AppConstants.Router.Service.F_SERVICE_SHOW_BIG_IMG,
                bundle
            )
        }
    })

    fun setData(data: PurchaseBean?) {
        if (data?.fileList?.size!! > 0) {
            data.fileParamUrl = data.fileList?.get(0)!!.fileUrl
        }
        bean.set(data)
    }

    fun WXGetApplicationInfo(
        applicaitonId: Int? = null
    ) {
        model.mTengYunHttpDataSource.selectApplication(
            GsonUtils.toJson(
                mapOf(
                    "applicaitonId" to applicaitonId
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<PurchaseBean>>() {
                override fun onResult(t: BaseBean<PurchaseBean>) {
                    if (t.state == 0) {
                        uc.loadCompleteEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    private fun checkApplication(
        applicaitonId: Int? = null,
        status: Int? = null
    ) {
        model.mTengYunHttpDataSource.checkApplication(
            GsonUtils.toJson(
                mapOf(
                    "applicaitonId" to applicaitonId,
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "status" to status
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        if (status == 1) {
                            showNormalToast("审批通过")
                        }
                        if (status == 2) {
                            showNormalToast("驳回成功")
                        }
                        if (status == 3) {
                            showNormalToast("撤回成功")
                        }
                        LiveBusCenter.postAssetResultReturnEvent(1)
//                        WXGetApplicationInfo(applicaitonId = applicaitonId)
                        uc.backCompleteEvent.postValue(1)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    private fun nextTaskProcess(
        taskUserId: String? = null
    ) {
        model.mTengYunHttpDataSource.nextTaskProcess(
            GsonUtils.toJson(
                mapOf(
                    "taskUserId" to taskUserId,
                    "taskDesc" to note.get()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.errorCode == 0) {
                        if (t.data == true) {
                            checkApplication(applicaitonId = applicaitonId, status = 1)
                        } else {
                            showNormalToast("审批通过")
                            LiveBusCenter.postAssetResultReturnEvent(1)
//                            WXGetApplicationInfo(applicaitonId = applicaitonId)
                            uc.backCompleteEvent.postValue(1)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
    private fun hangUpTaskProcess (
        taskUserId: String? = null
    ) {
        model.mTengYunHttpDataSource.hangUpTaskProcess(
            GsonUtils.toJson(
                mapOf(
                    "taskUserId" to taskUserId,
                    "taskDesc" to note.get()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.errorCode == 0) {
                        checkApplication(applicaitonId = applicaitonId, status = 2)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

}